<template>
	<view class="schedule-container">
		<!-- 顶部栏：月份选择 + 图标 -->
		<!-- <view class="top-bar">
			<text class="top-icon left-icon">☰</text>

			<view class="month-box" @click="openMonthPicker">
				<text class="month-text">{{ currentMonthText }}</text>
				<text class="month-arrow">▾</text>
			</view>

			<view class="top-right-icons">
				<text class="top-icon">📅</text>
				<text class="top-icon">⋯</text>
			</view>
		</view> -->

		<!-- 列表区域：使用 mescroll-uni -->
		<mescroll-uni class="my-mescroll"  top="-15" ref="mescrollRef" @init="mescrollInit" :down="downOption"
			:up="upOption" @down="downCallback" @up="upCallback" style="background: linear-gradient(to bottom, #e6f4ea 0%, #fdfaf4 100%);">


			<view class="weeks-wrap">
				<view class="week-section" v-for="week in weeks" :key="week.weekKey">
					<view class="week-range">{{ week.label }}</view>

					<view class="day-row" v-for="day in week.days" :key="day.date">
						<!-- 左侧：周几 + 日期 -->
						<view class="day-label">
							<text class="weekday">{{ day.weekday }}</text>
							<text class="day-num">{{ day.dayNum }}</text>
						</view>

						<!-- 右侧：课程条 -->
						<view class="course-list">
							<view class="course-pill" v-for="course in day.courses" :key="course.id"
								:style="{ backgroundColor: course.color }" @click="openCourse(course)">
								<text class="course-title">
									{{ course.title }}
									<text class="course-time">{{ course.timeRange }}</text>
								</text>
								<text v-if="course.isRepeat" class="course-repeat">⟳</text>
							</view>
						</view>
					</view>
				</view>
			</view>
		</mescroll-uni>


	</view>
</template>

<script>
	import MescrollMixin from '@/components/mescroll-uni/mescroll-mixins.js'
	import api from '@/api/api.js'

	export default {
		mixins: [MescrollMixin],
		data() {
			return {
				mescroll: undefined,
				// mescroll 配置（跟你参考页风格一致）
				downOption: {
					auto: false
				},
				upOption: {
					onScroll: true,
					use: true,
					auto: true,
					page: {
						num: 0,
						size: 10
					},
					noMoreSize: 1,
					empty: {
						tip: '本月暂无课程安排'
					}
				},
				startTime: '', // 查询开始时间，不选时默认今天
				// 业务数据
				weeks: [], // 按周分组后的数据
				rawListAll: [], // 所有页的原始 list 累加在这里

				studentId: '',
				currentMonth: new Date(),
				currentMonthText: ''
			}
		},
		onLoad(query) {
			// 接收上个页面传来的 studentId
			this.studentId = query.studentId || ''
			this.updateMonthText(this.currentMonth)

		},
		onShow() {
			this.mescroll && this.mescroll.resetUpScroll()
		},
		methods: {
			formatDateOnly(date) {
			    const y = date.getFullYear()
			    const m = (date.getMonth() + 1).toString().padStart(2, '0')
			    const d = date.getDate().toString().padStart(2, '0')
			    return `${y}-${m}-${d} 00:00:00`
			  },
			mescrollInit(mescroll) {
				this.mescroll = mescroll
			},
			// 下拉刷新：重置上拉
			downCallback(mescroll) {
				mescroll.resetUpScroll()
			},
			// 上拉加载：真正去调接口
			upCallback(page) {
				this.getSchedual(page)
			},

			/** 调课表接口，传入学生ID + 分页 */
			getSchedual(page) {
				const defaultStart = this.startTime || this.formatDateOnly(new Date())
				const params = {
					studentId: this.studentId,
					// 按你之前产量接口的习惯，这里用 page 传页码
					page: page.num,
					//startTime: defaultStart
					// 如果你后台用的是 pageNum/pageSize，就改成：
					// pageNum: page.num,
					// pageSize: page.size
				}

				api.getSchedual(params).then(res => {
					if (res.code === 200 && res.data) {
						const pageInfo = res.data
						const list = pageInfo.list || []
						const total = pageInfo.total || 0

						// 累加原始数据
						if (page.num === 1) {
							this.rawListAll = list
						} else {
							this.rawListAll = this.rawListAll.concat(list)
						}

						// 用全部原始数据构建本月的 weeks 结构
						this.weeks = this.buildWeeksFromRaw(this.rawListAll)

						// 用你习惯的 endBySize，交给 mescroll 计算是否还有下一页
						this.mescroll.endBySize(list.length, total)
					} else {
						uni.showToast({
							icon: 'none',
							title: res.msg || '请求失败'
						})
						this.weeks = []
						this.mescroll.endErr()
					}
				}).catch(() => {
					uni.showToast({
						icon: 'none',
						title: '网络异常'
					})
					this.weeks = []
					this.mescroll.endErr()
				})
			},

			/** 把扁平数组转成 weeks 结构（这里不用改） && d.getFullYear() === currentY && (d.getMonth() + 1) === currentM*/
			buildWeeksFromRaw(list) {
				const weekdayMap = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']

				const currentY = this.currentMonth.getFullYear()
				const currentM = this.currentMonth.getMonth() + 1

				const sorted = list
					.map(item => {
						const d = this.parseDate(item.classTimeBegin)
						return {
							raw: item,
							date: d
						}
					})
					.filter(obj => {
						const d = obj.date
						return d
					})
					.sort((a, b) => a.date - b.date)

				const weekMap = {}

				sorted.forEach(({
					raw,
					date
				}) => {
					if (!date) return
					const y = date.getFullYear()
					const m = date.getMonth() + 1
					const d = date.getDate()

					// 算这一周的周一作为 weekKey
					const monday = new Date(date.getTime())
					let day = monday.getDay()
					if (day === 0) day = 7
					monday.setDate(monday.getDate() - (day - 1))
					const weekKey = `${monday.getFullYear()}-${monday.getMonth() + 1}-${monday.getDate()}`

					if (!weekMap[weekKey]) {
						// 这一周的周一
						const mondayDay = monday.getDate()
						const mondayMonth = monday.getMonth() + 1
						// 这一周的周日 = 周一 + 6 天
						const sundayDate = new Date(monday.getTime())
						sundayDate.setDate(sundayDate.getDate() + 6)
						const sundayDay = sundayDate.getDate()

						weekMap[weekKey] = {
							weekKey,
							month: mondayMonth, // 周标题里的“几月”，用周一所在的月份
							mondayDay,
							sundayDay,
							daysMap: {}
						}
					}
					// 注意：不再用 minDay / maxDay


					const weekObj = weekMap[weekKey]

					const dayKey = `${y}-${m}-${d}`
					if (!weekObj.daysMap[dayKey]) {
						weekObj.daysMap[dayKey] = {
							date: dayKey,
							weekday: weekdayMap[date.getDay()],
							dayNum: d,
							courses: []
						}
					}

					const courseTitle = raw.classTopic ;
					const color = this.getCourseColor(raw.vocabularyId)
					const isRepeat = !!raw.totalVideo
					const timeRange = this.formatTimeRange(raw.classTimeBegin, raw.classTimeEnd)

					weekObj.daysMap[dayKey].courses.push({
						id: raw.id,
						title: courseTitle,
						color,
						isRepeat,
						timeRange,
						raw
					})
				})

				const weeks = Object.values(weekMap).map(week => {
					const days = Object.values(week.daysMap).sort((a, b) => a.dayNum - b.dayNum)

					// 一律用整周：周一 - 周日
					const label = `${week.month}月 ${week.mondayDay} - ${week.sundayDay}`

					return {
						weekKey: week.weekKey,
						label,
						days
					}
				})


				weeks.sort((a, b) => this.parseDate(a.weekKey) - this.parseDate(b.weekKey))
				return weeks
			},

			getCourseColor(vocabularyId) {
				switch (vocabularyId) {
					case '0基础':
					case '0基础主题课':
						return '#ff7a2c'
					case '剧场':
						return '#31a24c'
					case '复习':
						return '#2196f3'
					default:
						return '#7b3fbf'
				}
			},

			parseDate(str) {
				if (!str) return null
				const s = str.replace(/-/g, '/')
				const d = new Date(s)
				return isNaN(d.getTime()) ? null : d
			},

			formatTimeRange(begin, end) {
				const b = this.parseDate(begin)
				const e = this.parseDate(end)
				if (!b || !e) return ''
				const pad = n => (n < 10 ? '0' + n : '' + n)
				const bStr = `${pad(b.getHours())}:${pad(b.getMinutes())}`
				const eStr = `${pad(e.getHours())}:${pad(e.getMinutes())}`
				return `${bStr}-${eStr}`
			},

			updateMonthText(date) {
				const y = date.getFullYear()
				const m = date.getMonth() + 1
				this.currentMonthText = `${y}年${m}月`
			},

			openMonthPicker() {
				uni.showToast({
					title: '这里可以做月份选择~',
					icon: 'none'
				})
			},

			openCourse(course) {
				uni.showToast({
					title: course.title,
					icon: 'none'
				})
			},

			addCourse() {
				uni.showToast({
					title: '新增课程（待接页面）',
					icon: 'none'
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	.schedule-container {
		background: linear-gradient(to bottom, #e6f4ea 0%, #fdfaf4 100%);
		// flex: 1 1 auto;
		display: flex;
		justify-content: center;
		padding: 0 32upx;
		/* margin-top: -80upx; */
		//margin-top: -30upx;
		z-index: 1;
	}



	/* 顶部栏 */
	.top-bar {
		padding: 20upx 24upx 10upx;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.top-icon {
		font-size: 34upx;
		color: #222;
	}

	.left-icon {
		width: 80upx;
	}

	.month-box {
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: center;
	}

	.month-text {
		font-size: 32upx;
		font-weight: 600;
		color: #111;
	}

	.month-arrow {
		font-size: 24upx;
		margin-left: 8upx;
		color: #666;
	}

	.top-right-icons {
		width: 120upx;
		display: flex;
		align-items: center;
		justify-content: flex-end;
	}

	.top-right-icons .top-icon+.top-icon {
		margin-left: 18upx;
	}

	/* 周分段 */
	.weeks-wrap {
		background: linear-gradient(to bottom, #e6f4ea 0%, #fdfaf4 100%);
		padding: 0 24upx 110upx;
	}

	.week-section {
		margin-top: 16upx;
	}

	.week-range {
		font-size: 24upx;
		color: #888;
		margin: 16upx 0 8upx;
	}

	/* 每天 */
	.day-row {
		display: flex;
		padding: 8upx 0 18upx;
	}

	.day-label {
		width: 90upx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: flex-start;
		padding-top: 10upx;
	}

	.weekday {
		font-size: 22upx;
		color: #999;
	}

	.day-num {
		font-size: 34upx;
		font-weight: 600;
		color: #333;
	}

	/* 课程条区域 */
	.course-list {
		flex: 1;
		display: flex;
		flex-direction: column;
		gap: 10upx;
	}

	.course-pill {
		min-height: 88upx;
		border-radius: 20upx;
		padding: 0 30upx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		color: #ffffff;
		font-size: 28upx;
	}

	.course-title {
		flex: 1;
	}

	.course-time {
		font-size: 24upx;
		margin-left: 16upx;
		opacity: 0.9;
	}

	/* 循环小图标 */
	.course-repeat {
		font-size: 24upx;
		opacity: 0.9;
	}

	/* 悬浮新增按钮 */
	.fab {
		position: fixed;
		right: 40upx;
		bottom: 140upx;
		width: 110upx;
		height: 110upx;
		border-radius: 999upx;
		background-color: #2196f3;
		box-shadow: 0 10upx 20upx rgba(0, 0, 0, 0.18);
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.fab-plus {
		font-size: 60upx;
		line-height: 1;
		color: #ffffff;
	}
</style>